package com.googlecode.chigs.web.config.configrevision;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.wizard.WizardModel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.target.basic.RedirectRequestTarget;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import brix.BrixNodeModel;
import brix.web.nodepage.BrixNodeWebPage;
import brix.web.nodepage.BrixPageParameters;

import com.googlecode.chigs.domain.ConfigRevision;
import com.googlecode.chigs.domain.Configuration;
import com.googlecode.chigs.domain.Product;
import com.googlecode.chigs.domain.Revision;
import com.googlecode.chigs.repository.ChigsFacade;
import com.googlecode.chigs.web.ChigsApplication;
import com.googlecode.chigs.web.common.wizard.DefaultWizard;
import com.googlecode.chigs.web.config.configpair.UpdateConfigPairStep;
import com.googlecode.chigs.web.config.configuration.UpdateConfigurationStep;

@AuthorizeInstantiation("ROLE_USER")
public class UpdateConfigRevisionWizard extends DefaultWizard {
	private static Logger log = LoggerFactory.getLogger(UpdateConfigurationStep.class);

	@SpringBean
	private ChigsFacade chigs;

	private final ConfigRevision configRevision;
	private final Product product;
	private Configuration configuration;
	private List<Revision> changes;

	public UpdateConfigRevisionWizard(String id, Configuration configuration, Product product) {
		super(id, true);
		
		this.product = product;
		this.configuration = configuration;
		this.changes = new ArrayList<Revision>();
		
		this.configRevision = chigs.loadLatestConfigRevision(configuration);
		init();
	}

	private void init() {
		setDefaultModel(new CompoundPropertyModel<UpdateConfigRevisionWizard>(this));
		
		WizardModel model = new WizardModel();
		model.add(new UpdateConfigurationStep(this.configRevision, this.product, this.changes));
		model.add(new UpdateConfigPairStep(this.configRevision, this.changes));
		init(model);
	}
	
	@Override
	public void onCancel() {
		returnToManagement();
	}
	
	@Override
	public void onFinish() {
		try {
			if (isEditable()) {
				List<Revision> newrevs = new ArrayList<Revision>(changes);
				for (Revision revision : configRevision.getRevisions()) {
					boolean add = true;
					for (Revision changerev : changes) {
						if (changerev.getModule().getId().longValue() == revision.getModule().getId().longValue()) {
							add = false;
							break;
						}
					}
					if (add) {
						newrevs.add(revision);
					}
				}
				if (log.isDebugEnabled()) {
					log.debug("old revisions: " + configRevision.getRevisions() + " for config revision: " + configRevision);
					log.debug("new revisions: " + changes + " for config revision: " + configRevision);
				}
				configRevision.setRevisions(newrevs);
				
				chigs.saveConfigRevision(configRevision);
				getSession().info(new StringResourceModel("save.success", UpdateConfigRevisionWizard.this, null).getString());
			}
			returnToManagement();
		} catch (Exception e) {
			log.error(e.getMessage() != null ? e.getMessage() : e.toString(), e);
			error(e.getMessage() != null ? e.getMessage() : e.toString());
		}
	}

	private void returnToManagement() {
		if (isEditable()) {
			getRequestCycle().setRequestTarget(new RedirectRequestTarget("/configuration/configurations.html"));
		} else {
			BrixPageParameters params = new BrixPageParameters();
			params.addQueryParam("product", product.getId().toString());
			params.addQueryParam("configuration", configuration.getId().toString());
			BrixNodeModel model = ((ChigsApplication) getApplication()).getBrixLink("/configuration/revisions.html");
			getRequestCycle().setRequestTarget(new RedirectRequestTarget(params.urlFor(new BrixNodeWebPage(model))));
		}
	}
}

